package com.qyhl.module_home.city;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.weather.LocalWeatherForecastResult;
import com.amap.api.services.weather.LocalWeatherLive;
import com.amap.api.services.weather.LocalWeatherLiveResult;
import com.amap.api.services.weather.WeatherSearch;
import com.amap.api.services.weather.WeatherSearchQuery;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.example.sdk.statisticssdk.StatisticsMainInit;
import com.gyf.immersionbar.ImmersionBar;
import com.qyhl.module_home.R;
import com.qyhl.module_home.R2;
import com.qyhl.webtv.basiclib.base.BaseFragment;
import com.qyhl.webtv.basiclib.utils.DateUtils;
import com.qyhl.webtv.basiclib.utils.MPermissionUtils;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.basiclib.utils.ToastUtils;
import com.qyhl.webtv.basiclib.utils.dialog.CommonDialog;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.constant.AppConfigConstant;
import com.qyhl.webtv.commonlib.entity.home.CityBean;
import com.qyhl.webtv.commonlib.utils.action.ActionConstant;
import com.qyhl.webtv.commonlib.utils.action.ActionLogUtils;
import com.qyhl.webtv.commonlib.utils.config.AppConfigUtil;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.qyhl.webtv.commonlib.utils.view.ListViewUtils;
import com.qyhl.webtv.commonlib.utils.view.MyGridView;
import com.qyhl.webtv.commonlib.utils.view.MyListView;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.umeng.analytics.MobclickAgent;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.abslistview.CommonAdapter;
import com.zhy.adapter.abslistview.ViewHolder;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import es.dmoral.toasty.Toasty;

/**
 * Created by qyhl on 2017/11/7.
 * 城事
 */

public class CityFragment extends BaseFragment implements CityContract.CityView {
    @BindView(R2.id.current_temperature)
    TextView currentTemperature;
    @BindView(R2.id.location)
    TextView location;
    @BindView(R2.id.weather_state)
    TextView weatherState;
    @BindView(R2.id.weather_wind_power)
    TextView weatherWindPower;
    @BindView(R2.id.weather_wind)
    TextView weatherWind;
    @BindView(R2.id.weather_water_power)
    TextView weatherWaterPower;
    @BindView(R2.id.weather_water)
    TextView weatherWater;
    @BindView(R2.id.weather_update_time)
    TextView weatherUpdateTime;
    @BindView(R2.id.weather_update)
    TextView weatherUpdate;
    @BindView(R2.id.weather_layout)
    RelativeLayout weatherLayout;
    @BindView(R2.id.city_header_gv)
    MyGridView cityHeaderGv;
    @BindView(R2.id.city_fragment_lv)
    MyListView listView;
    @BindView(R2.id.city_refresh)
    SmartRefreshLayout cityRefresh;
    @BindView(R2.id.city_loadmask)
    LoadingLayout cityLoadmask;
    @BindView(R2.id.city_title)
    LinearLayout mCityTitle;

    private View view;
    private CityPresenter mPresenter;

    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;

    private String cityName, provinceName;
    private WeatherSearchQuery mquery;
    private WeatherSearch mWeatherSearch;
    private LocalWeatherLive weatherlive;

    private List<CityBean.MenuItems> itemsList;
    private List<CityBean.TopMenus> menusList;
    private RequestOptions options;
    private BodyAdapter bodyAdapter;

    private boolean isFirst = true;

    private boolean isFirstCount = true;

    private boolean isFromActivity;

    public void setFromActivity(boolean fromActivity) {
        isFromActivity = fromActivity;
    }

    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return view = inflater.inflate(R.layout.home_fragment_city, null);
    }

    @Override
    protected void create() {
        if (isFromActivity) {
            if (!MPermissionUtils.checkPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION})) {
                new CommonDialog.Builder(getActivity())
                        .setTitle("权限申请", R.color.global_black_lv1)
                        .setMessage("位置权限，用于为您推荐本地新闻、发表信息时展示位置信息等", R.color.global_black_lv2)
                        .setPositiveButton("确定", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                MPermissionUtils.requestPermissionsResult(getActivity(), 1, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, new MPermissionUtils.OnPermissionListener() {
                                    @Override
                                    public void onPermissionGranted() {
                                        mLocationClient.startLocation();
                                    }

                                    @Override
                                    public void onPermissionDenied() {
                                        MPermissionUtils.showTipsDialog(getContext());
                                    }
                                });
                            }
                        }, R.color.global_base)
                        .setNegativeButton("取消", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {

                            }
                        }, R.color.global_gray_lv2).show();
            }
        }
        mPresenter = new CityPresenter(this);
        initView();
        setListeners();
        loadData();
    }

    @Override
    public void initImmersionBar() {
        super.initImmersionBar();
        ImmersionBar.with(this)
                .statusBarDarkFont(true, 0.2f)
                .titleBar(mCityTitle)
                .init();

    }

    @Override
    protected void setListener() {

    }

    @Override
    protected void onFirstVisible() {
        if (!MPermissionUtils.checkPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION})) {
            new CommonDialog.Builder(getActivity())
                    .setTitle("权限申请", R.color.global_black_lv1)
                    .setMessage("位置权限，用于为您推荐本地新闻、发表信息时展示位置信息等", R.color.global_black_lv2)
                    .setPositiveButton("确定", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            MPermissionUtils.requestPermissionsResult(getActivity(), 1, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, new MPermissionUtils.OnPermissionListener() {
                                @Override
                                public void onPermissionGranted() {
                                    mLocationClient.startLocation();
                                }

                                @Override
                                public void onPermissionDenied() {
                                    MPermissionUtils.showTipsDialog(getContext());
                                }
                            });
                        }
                    }, R.color.global_base)
                    .setNegativeButton("取消", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                        }
                    }, R.color.global_gray_lv2).show();
        }
    }

    @Override
    protected void onVisible() {

    }

    @Override
    protected void onHide() {

    }

    public static CityFragment newInstance() {
        return new CityFragment();
    }

    public static CityFragment newInstance(boolean isFromActivity) {
        CityFragment cityFragment = new CityFragment();
        cityFragment.setFromActivity(isFromActivity);
        return cityFragment;
    }


    /**
     * 加载数据
     */
    private void loadData() {
        //下拉刷新
        mPresenter.getData();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            ActionLogUtils.getInstance().onResume(this.getActivity(), ActionConstant.CIRCLEHOME);
        } else {
            ActionLogUtils.getInstance().onPause(this.getActivity(), ActionConstant.CIRCLEHOME);
        }
    }

    /**
     * 初始化
     */
    private void initView() {
        itemsList = new ArrayList<>();
        menusList = new ArrayList<>();

        cityLoadmask.setStatus(LoadingLayout.Loading);
        //配置刷新
        cityRefresh.setDisableContentWhenRefresh(true);
        cityRefresh.setRefreshHeader(new MaterialHeader(getContext()));
        cityRefresh.setEnableLoadMore(false);

        //定位配置
        mLocationOption = new AMapLocationClientOption(); //初始化AMapLocationClientOption对象
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);//设置定位模式为AMapLocationMode.Battery_Saving，低功耗模式。
        mLocationOption.setNeedAddress(true); //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setHttpTimeOut(15000); //单位是毫秒，默认30000毫秒，建议超时时间不要低于8000毫秒。
        mLocationOption.setInterval(2000);
        try {
            mLocationClient = new AMapLocationClient(getContext().getApplicationContext());
        } catch (Exception e) {
            e.printStackTrace();
        }
        mLocationClient.setLocationOption(mLocationOption); //给定位客户端对象设置定位参数
        mLocationClient.setLocationListener(mLocationListener);  //设置定位回调监听

        //glide 配置
        options = new RequestOptions()
                .placeholder(R.drawable.cover_square_default)
                .error(R.drawable.cover_square_default);

        cityHeaderGv.setNumColumns(4);
        cityHeaderGv.setAdapter(new CommonAdapter<CityBean.TopMenus>(getContext(), R.layout.home_item_city_one, menusList) {
            @Override
            protected void convert(ViewHolder viewHolder, CityBean.TopMenus item, int position) {
                TextView title = viewHolder.getView(R.id.title);
                ImageView icon = viewHolder.getView(R.id.icon);

                title.setText(item.getMenuName());
                Glide.with(getContext().getApplicationContext())
                        .load(item.getMenuImg())
                        .apply(options)
                        .into(icon);
            }
        });

        bodyAdapter = new BodyAdapter(getContext());
        listView.setAdapter(bodyAdapter);
    }

    /**
     * 监听
     */
    private void setListeners() {
        //刷新
        cityRefresh.setOnRefreshListener(refreshlayout -> {
            //启动定位
            mLocationClient.startLocation();
            mPresenter.getData();
        });

        //重新获取信息
        cityLoadmask.setOnReloadListener(v -> {
            //启动定位
            mLocationClient.startLocation();
            mPresenter.getData();
        });

        //头部栏目监听
        cityHeaderGv.setOnItemClickListener((parent, view, position, id) -> {
            CityBean.TopMenus bean = menusList.get(position);
            navigationSkip(bean);
        });
    }

    /**
     * 跳转
     *
     * @param bean
     */
    private void navigationSkip(CityBean.TopMenus bean) {
        switch (bean.getTypeId()) {
            case 1:
                if (bean.getStyleId() == 1) {//资讯样式
                    Bundle bundle = new Bundle();
                    bundle.putString("title", bean.getMenuName());
                    bundle.putString("id", bean.getSecondId() + "");
                    bundle.putString("type", "1");
                    RouterManager.router(ARouterPathConstant.INFO, bundle);

                } else { //节目样式

                    Bundle bundle = new Bundle();
                    bundle.putString("title", bean.getMenuName());
                    bundle.putString("menuId", bean.getSecondId() + "");
                    bundle.putString("type", "1");
                    RouterManager.router(ARouterPathConstant.PROGRAM, bundle);

                }
                break;
            case 2://活动列表
            {
                Bundle bundle = new Bundle();
                bundle.putString("title", bean.getMenuName());
                RouterManager.router(ARouterPathConstant.ACTIVITY_LIST_TEMP, bundle);
            }
            break;
            case 3://直播列表
            {
                Bundle bundle = new Bundle();
                bundle.putString("title", bean.getMenuName());
                RouterManager.router(ARouterPathConstant.LIVELIST, bundle);
            }
            break;
            case 4://链接
            {
                Bundle bundle = new Bundle();
                bundle.putString("title", bean.getMenuName());
                bundle.putString("url", bean.getUrl());
                bundle.putString("id", "");
                int hasShare = (int) AppConfigUtil.getInstance().getConValue(AppConfigConstant.LINK_URL_SHARE);
                if (hasShare == 1) {
                    bundle.putBoolean("hasShare", false);
                } else {
                    bundle.putBoolean("hasShare", true);
                }
                RouterManager.router(ARouterPathConstant.NEWS_TITLE, bundle);
            }
            break;
            case 5://电商
                break;
            case 6://新闻列表
            {
                Bundle bundle = new Bundle();
                bundle.putString("title", bean.getMenuName());
                bundle.putString("id", bean.getUrl());
                RouterManager.router(ARouterPathConstant.NEWS_LIST, bundle);
            }
            break;
            case 7://新趣汇
            {
                RouterManager.router(ARouterPathConstant.GOOD_LIFE);
            }
            break;
            case 8://小视频
            {
                RouterManager.router(ARouterPathConstant.SMALLVIDEO);
            }
            break;
            case 9:
                switch (bean.getStyleId()) {
                    case 1://乡镇
                    {
                        Bundle bundle = new Bundle();
                        bundle.putString("title", bean.getMenuName());
                        bundle.putString("sectionId", bean.getUrl());
                        RouterManager.router(ARouterPathConstant.TOWN_LIST, bundle);
                    }
                    break;
                    case 2://政务
                    {
                        Bundle bundle = new Bundle();
                        bundle.putString("title", bean.getMenuName());
                        bundle.putString("sectionId", bean.getUrl());
                        RouterManager.router(ARouterPathConstant.GOV_LIST, bundle);
                    }

                    break;
                    case 3://专题
                    {
                        Bundle bundle = new Bundle();
                        bundle.putString("title", bean.getMenuName());
                        bundle.putString("sectionId", bean.getUrl());
                        RouterManager.router(ARouterPathConstant.SPECIAL, bundle);
                    }
                    break;
                    case 4://富顺乡镇样式
                    {
                        Bundle bundle = new Bundle();
                        bundle.putString("title", bean.getMenuName());
                        bundle.putString("sectionId", bean.getUrl());
                        RouterManager.router(ARouterPathConstant.UNION_TOWN3, bundle);
                        ActionLogUtils.getInstance().onEvent(ActionConstant.FLOWSCENE, ActionConstant.HOME, ActionConstant.TOWNDETAIL);
                    }
                    break;
                    default:
                        Toasty.normal(getContext(), "类型出错！", Toast.LENGTH_SHORT).show();
                        break;
                }
                break;
            case 10://图文直播
            {
                Bundle bundle = new Bundle();
                bundle.putString("id", bean.getUrl());
                RouterManager.router(ARouterPathConstant.TELE_VIDEO_ACTIVITY, bundle);
            }
            break;
            case 11://电视直播  1.广播 2.电视//---a
            {
                Bundle bundle = new Bundle();
                bundle.putString("id", bean.getUrl());
                bundle.putString("title", bean.getMenuName());
                bundle.putString("type", bean.getStyleId() + "");
                RouterManager.router(ARouterPathConstant.NEWLIVE_LIST, bundle);

            }
            break;
            case 12://传统直播混合列表
            {
                Bundle bundle = new Bundle();
                bundle.putString("title", bean.getMenuName());
                bundle.putString("type", "");
                RouterManager.router(ARouterPathConstant.MIX_LIVE, bundle);
                ActionLogUtils.getInstance().onEvent(ActionConstant.FLOWSCENE, ActionConstant.HOME, ActionConstant.MIXLIVE);
            }
            break;
            case 13:  //传统直播音频列表
            {
                Bundle bundle = new Bundle();
                bundle.putString("title", bean.getMenuName());
                bundle.putString("type", "2");
                RouterManager.router(ARouterPathConstant.MIX_LIVE, bundle);
                ActionLogUtils.getInstance().onEvent(ActionConstant.FLOWSCENE, ActionConstant.HOME, ActionConstant.MIXLIVE);
            }
            break;
            case 14: //传统直播视频列表
            {
                Bundle bundle = new Bundle();
                bundle.putString("title", bean.getMenuName());
                bundle.putString("type", "1");
                RouterManager.router(ARouterPathConstant.MIX_LIVE, bundle);
                ActionLogUtils.getInstance().onEvent(ActionConstant.FLOWSCENE, ActionConstant.HOME, ActionConstant.MIXLIVE);
            }
            break;
            case 15://新乡镇样式//---a
            {
                Bundle bundle = new Bundle();
                bundle.putString("title", bean.getMenuName());
                bundle.putString("id", bean.getUrl());
                RouterManager.router(ARouterPathConstant.UNION_TOWN2, bundle);
                ActionLogUtils.getInstance().onEvent(ActionConstant.FLOWSCENE, ActionConstant.HOME, ActionConstant.TOWNDETAIL);
            }
            break;
            case 16://新活动
            {
                Bundle bundle = new Bundle();
                bundle.putString("title", bean.getMenuName());
                RouterManager.router(ARouterPathConstant.ACTIVITY_LIST_TEMP, bundle);
            }
            break;
            case 17://开票有喜
            {
                Bundle bundle = new Bundle();
                bundle.putString("title", bean.getMenuName());
                bundle.putString("id", bean.getSecondId() + "");
                RouterManager.router(ARouterPathConstant.LUCK_DRAW, bundle);
            }
            break;
            case 18://城事
            {
                Bundle bundle = new Bundle();
                bundle.putString("title", bean.getMenuName());
                RouterManager.router(ARouterPathConstant.CITY, bundle);
            }
            break;
            case 19://问答
            {
                Bundle bundle = new Bundle();
                bundle.putString("title", bean.getMenuName());
                RouterManager.router(ARouterPathConstant.SCOOP_HOME, bundle);
            }
            break;
            case 21://百事通
            {
                RouterManager.router(ARouterPathConstant.BESTONE_TYPE);
            }
            break;
            case 22: {
                Bundle bundle = new Bundle();
                bundle.putString("title", bean.getMenuName());
                RouterManager.router(ARouterPathConstant.NEWLIVE_LIST, bundle);
            }
            break;
            case 63: {
                boolean b = checkAppInstalled(getActivity(), "com.ss.android.ugc.aweme");
                if (b) {
                    Intent intent = new Intent();
                    intent.setData(Uri.parse("snssdk1128://user/profile/" + bean.getUrl()));
                    startActivity(intent);
                } else {
                    ToastUtils.showToast(getActivity(), "未安装此应用");
                }
            }
            break;
            default:
                break;
        }
    }

    private boolean checkAppInstalled(Context context, String pkgName) {
        if (pkgName == null || pkgName.isEmpty()) {
            return false;
        }
        final PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> info = packageManager.getInstalledPackages(0);
        if (info == null || info.isEmpty())
            return false;
        for (int i = 0; i < info.size(); i++) {
            if (pkgName.equals(info.get(i).packageName)) {
                return true;
            }
        }
        return false;
    }

    private void navigationSkip(CityBean.MenuItems.MenuItem bean) {
        switch (bean.getItemType()) {
            case 1:
                if (bean.getStyleId() == 1) {//资讯样式
                    Bundle bundle = new Bundle();
                    bundle.putString("title", bean.getItemName());
                    bundle.putString("id", bean.getItemSectionId() + "");
                    bundle.putString("type", "1");
                    RouterManager.router(ARouterPathConstant.INFO, bundle);
                } else { //节目样式//---a
                    Bundle bundle = new Bundle();
                    bundle.putString("title", bean.getItemName());
                    bundle.putString("id", bean.getItemSectionId() + "");
                    bundle.putString("type", "1");
                    RouterManager.router(ARouterPathConstant.PROGRAM, bundle);
                }
                ActionLogUtils.getInstance().onEvent(ActionConstant.FLOWSCENE, ActionConstant.HOME, ActionConstant.INFORMATION);
                break;
            case 2://活动列表//---f
            {
                Bundle bundle = new Bundle();
                bundle.putString("title", bean.getItemName());
                RouterManager.router(ARouterPathConstant.ACTIVITY_LIST_TEMP, bundle);
            }
            break;
            case 3://直播列表//---f
            {
                Bundle bundle = new Bundle();
                bundle.putString("title", bean.getItemName());
                RouterManager.router(ARouterPathConstant.LIVELIST, bundle);
                ActionLogUtils.getInstance().onEvent(ActionConstant.FLOWSCENE, ActionConstant.HOME, ActionConstant.LIVELIST);
            }
            break;
            case 4://链接//---f
            {
                Bundle bundle = new Bundle();
                bundle.putString("title", bean.getItemName());
                bundle.putString("url", bean.getItemOuturl());
                bundle.putString("id", "");
                int hasShare = (int) AppConfigUtil.getInstance().getConValue(AppConfigConstant.LINK_URL_SHARE);
                if (hasShare == 1) {
                    bundle.putBoolean("hasShare", false);
                } else {
                    bundle.putBoolean("hasShare", true);
                }
                RouterManager.router(ARouterPathConstant.NEWS_TITLE, bundle);
            }
            break;
            case 5://电商
                break;
            case 6://新闻列表//---
            {
                Bundle bundle = new Bundle();
                bundle.putString("title", bean.getItemName());
                bundle.putString("id", bean.getItemSectionId() + "");
                RouterManager.router(ARouterPathConstant.NEWS_LIST, bundle);
                ActionLogUtils.getInstance().onEvent(ActionConstant.FLOWSCENE, ActionConstant.HOME, ActionConstant.SECTIONS);
            }
            break;
            case 7://新趣汇//---a
            {
                RouterManager.router(ARouterPathConstant.GOOD_LIFE);
                ActionLogUtils.getInstance().onEvent(ActionConstant.FLOWSCENE, ActionConstant.HOME, ActionConstant.GOODLIFE);
            }
            break;
            case 8://小视频//---a
            {
                RouterManager.router(ARouterPathConstant.SMALLVIDEO);
                ActionLogUtils.getInstance().onEvent(ActionConstant.FLOWSCENE, ActionConstant.HOME, ActionConstant.SMALLVIDEO);
            }
            break;
            case 9:
                switch (bean.getStyleId()) {
                    case 1://乡镇//---a
                    {
                        Bundle bundle = new Bundle();
                        bundle.putString("title", bean.getItemName());
                        bundle.putString("sectionId", bean.getItemSectionId() + "");
                        RouterManager.router(ARouterPathConstant.TOWN_LIST, bundle);
                        ActionLogUtils.getInstance().onEvent(ActionConstant.FLOWSCENE, ActionConstant.HOME, ActionConstant.TOWNDETAIL);
                    }
                    break;
                    case 2://政务//---a
                    {
                        Bundle bundle = new Bundle();
                        bundle.putString("title", bean.getItemName());
                        bundle.putString("sectionId", bean.getItemSectionId() + "");
                        RouterManager.router(ARouterPathConstant.GOV_LIST, bundle);
                    }
                    ActionLogUtils.getInstance().onEvent(ActionConstant.FLOWSCENE, ActionConstant.HOME, ActionConstant.GOVDETAIL);
                    break;
                    case 3://专题//---a
                    {
                        Bundle bundle = new Bundle();
                        bundle.putString("title", bean.getItemName());
                        bundle.putString("sectionId", bean.getItemSectionId() + "");
                        RouterManager.router(ARouterPathConstant.SPECIAL, bundle);
                        ActionLogUtils.getInstance().onEvent(ActionConstant.FLOWSCENE, ActionConstant.HOME, ActionConstant.SPECIADETAIL);
                    }
                    break;
                    case 4://富顺乡镇样式
                    {
                        Bundle bundle = new Bundle();
                        bundle.putString("title", bean.getItemName());
                        bundle.putString("sectionId", bean.getItemSectionId() + "");
                        RouterManager.router(ARouterPathConstant.UNION_TOWN3, bundle);
                        ActionLogUtils.getInstance().onEvent(ActionConstant.FLOWSCENE, ActionConstant.HOME, ActionConstant.TOWNDETAIL);
                    }
                    break;
                    default:
                        Toasty.normal(getContext(), "类型出错！", Toast.LENGTH_SHORT).show();
                        break;
                }
                break;
            case 10://图文直播//---f
            {
                Bundle bundle = new Bundle();
                bundle.putString("title", bean.getItemName());
                RouterManager.router(ARouterPathConstant.TELETEXT_LIST, bundle);
                ActionLogUtils.getInstance().onEvent(ActionConstant.FLOWSCENE, ActionConstant.HOME, ActionConstant.TELETEXTLIST);
            }
            break;
            case 11://电视直播  1.广播 2.电视//---a
            {
                Bundle bundle = new Bundle();
                bundle.putString("title", bean.getItemName());
                bundle.putString("id", bean.getItemSectionId() + "");
                bundle.putString("type", bean.getStyleId() + "");
                RouterManager.router(ARouterPathConstant.NEWLIVE_LIST, bundle);
            }
            break;
            case 12://传统直播混合列表
            {
                Bundle bundle = new Bundle();
                bundle.putString("title", bean.getItemName());
                bundle.putString("type", "");
                RouterManager.router(ARouterPathConstant.MIX_LIVE, bundle);
                ActionLogUtils.getInstance().onEvent(ActionConstant.FLOWSCENE, ActionConstant.HOME, ActionConstant.MIXLIVE);
            }
            break;
            case 13:  //传统直播音频列表
            {
                Bundle bundle = new Bundle();
                bundle.putString("title", bean.getItemName());
                bundle.putString("type", "2");
                RouterManager.router(ARouterPathConstant.MIX_LIVE, bundle);
                ActionLogUtils.getInstance().onEvent(ActionConstant.FLOWSCENE, ActionConstant.HOME, ActionConstant.MIXLIVE);
            }
            break;
            case 14: //传统直播视频列表
            {
                Bundle bundle = new Bundle();
                bundle.putString("title", bean.getItemName());
                bundle.putString("type", "1");
                RouterManager.router(ARouterPathConstant.MIX_LIVE, bundle);
                ActionLogUtils.getInstance().onEvent(ActionConstant.FLOWSCENE, ActionConstant.HOME, ActionConstant.MIXLIVE);
            }
            break;
            case 15://新乡镇样式//---
            {
                Bundle bundle = new Bundle();
                bundle.putString("title", bean.getItemName());
                bundle.putString("id", bean.getItemSectionId() + "");
                RouterManager.router(ARouterPathConstant.UNION_TOWN2, bundle);
                ActionLogUtils.getInstance().onEvent(ActionConstant.FLOWSCENE, ActionConstant.HOME, ActionConstant.TOWNDETAIL);
            }
            break;
            case 16://新活动
            {
                Bundle bundle = new Bundle();
                bundle.putString("title", bean.getItemName());
                RouterManager.router(ARouterPathConstant.ACTIVITY_LIST_TEMP, bundle);
            }
            break;
            case 17://开票有喜
            {
                Bundle bundle = new Bundle();
                bundle.putString("title", bean.getItemName());
                bundle.putString("id", bean.getItemSectionId() + "");
                RouterManager.router(ARouterPathConstant.LUCK_DRAW, bundle);
            }
            break;
            case 18://城事
            {
                Bundle bundle = new Bundle();
                bundle.putString("title", bean.getItemName());
                RouterManager.router(ARouterPathConstant.CITY, bundle);
            }
            break;
            case 19://问答
            {
                Bundle bundle = new Bundle();
                bundle.putString("title", bean.getItemName());
                RouterManager.router(ARouterPathConstant.SCOOP_HOME, bundle);
            }
            break;
            case 21://百事通
            {
                RouterManager.router(ARouterPathConstant.BESTONE_TYPE);
            }
            break;
            case 63: {
                boolean b = checkAppInstalled(getActivity(), "com.ss.android.ugc.aweme");
                if (b) {
                    Intent intent = new Intent();
                    intent.setData(Uri.parse("snssdk1128://user/profile/108651415288"));
                    startActivity(intent);
                } else {
                    showToast("未安装此应用");
                }
            }
            break;
            default: {
                Bundle bundle = new Bundle();
                bundle.putString("title", bean.getItemName());
                RouterManager.router(ARouterPathConstant.ACTIVITY_DEFAULT, bundle);
            }
            break;
        }
    }


    @Override
    public void setData(CityBean bean) {
        cityRefresh.finishRefresh();
        cityLoadmask.setStatus(LoadingLayout.Success);

        menusList.clear();
        if (bean.getTopMenus() != null && bean.getTopMenus().size() > 0) {
            menusList.addAll(bean.getTopMenus());
        }
        int index = 0;
        if (menusList.size() > 0) {
            index = 0;
        } else if (menusList.size() % 4 == 0) {
            index = menusList.size() / 4;
        } else {
            index = menusList.size() / 4 + 1;
        }

        ListViewUtils.calGridViewWidthAndHeigh(4, cityHeaderGv, index * 100);

        itemsList.clear();
        if (bean.getMenuItems() != null && bean.getMenuItems().size() > 0) {
            itemsList.addAll(bean.getMenuItems());
        }
        bodyAdapter.setList(itemsList);
        bodyAdapter.notifyDataSetChanged();


    }

    @Override
    public void setError(String msg) {
        cityLoadmask.setErrorText(msg);
        cityLoadmask.setStatus(LoadingLayout.Error);
        resetWeather();
    }

    @Override
    public void setEmpty(String msg) {
        cityLoadmask.setEmptyText(msg);
        cityLoadmask.setStatus(LoadingLayout.Empty);
        resetWeather();
    }

    @Override
    public void setNetError(String msg) {
        cityLoadmask.setNoNetworkText(msg);
        cityLoadmask.setStatus(LoadingLayout.No_Network);
        resetWeather();
    }

    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(final AMapLocation aMapLocation) {
            cityName = aMapLocation.getCity();
            provinceName = aMapLocation.getProvince();
            if (StringUtils.isNotEmpty(cityName)) {
                if (isFirstCount) {
                    isFirstCount = false;
                    //四川融媒统计
                    if (CommonUtils.getInstance().getSite() == 148 || CommonUtils.getInstance().getSite() == 145) {
                        StatisticsMainInit.appStart(CommonUtils.getInstance().getUMChannelId(), cityName + "|" + aMapLocation.getDistrict());
                    }
                }

                location.setText(provinceName + cityName);
                //检索参数为城市和天气类型，实况天气为WEATHER_TYPE_LIVE、天气预报为WEATHER_TYPE_FORECAST
                mquery = new WeatherSearchQuery(cityName, WeatherSearchQuery.WEATHER_TYPE_LIVE);
                try {
                    mWeatherSearch = new WeatherSearch(getContext());
                } catch (AMapException e) {
                    e.printStackTrace();
                    Log.i("@@@", e.toString());
                }
                mWeatherSearch.setOnWeatherSearchListener(new WeatherSearch.OnWeatherSearchListener() {
                    @Override
                    public void onWeatherLiveSearched(LocalWeatherLiveResult localWeatherLiveResult, int rCode) {
                        if (rCode == 1000) {
                            if (localWeatherLiveResult != null && localWeatherLiveResult.getLiveResult() != null) {
                                weatherlive = localWeatherLiveResult.getLiveResult();
                                currentTemperature.setText(weatherlive.getTemperature() + "°C");
                                weatherUpdateTime.setText(DateUtils.detailDateTranslate(weatherlive.getReportTime()));
                                weatherState.setText(weatherlive.getWeather());
                                weatherWind.setText(weatherlive.getWindDirection() + "风");
                                weatherWindPower.setText(weatherlive.getWindPower() + "级");
                                weatherWaterPower.setText(weatherlive.getHumidity() + "%");
                                mLocationClient.stopLocation();//停止定位
                            } else {
                                resetWeather();
                            }
                        } else {
                            resetWeather();
                        }
                    }

                    @Override
                    public void onWeatherForecastSearched(LocalWeatherForecastResult localWeatherForecastResult, int i) {

                    }
                });
                mWeatherSearch.setQuery(mquery);
                mWeatherSearch.searchWeatherAsyn(); //异步搜索
            } else {
                if (isFirst) {
                    Toasty.normal(getContext(), "定位失败，当前网络信号较差，请尝试到空旷场地或打开GPS后重试", Toast.LENGTH_LONG).show();
                    isFirst = false;
                }

            }
        }
    };

    /**
     * 重新设置天气
     */
    private void resetWeather() {
        weatherWindPower.setText("---");
        weatherWind.setText("---");
        weatherWaterPower.setText("---");
        weatherUpdateTime.setText("---");
        weatherState.setText("---");
        currentTemperature.setText("---");
    }


    /**
     * 适配器
     */
    class BodyAdapter extends BaseAdapter {
        List<CityBean.MenuItems> list;
        Context context;
        private List<CityBean.MenuItems.MenuItem> tlist;
        private BodyItemAdapter bodyItemAdapter;

        public BodyAdapter(Context context) {
            this.context = context;
        }

        public List<CityBean.MenuItems> getList() {
            return list;
        }

        public void setList(List<CityBean.MenuItems> list) {
            this.list = list;
        }

        @Override
        public int getCount() {
            return list == null ? 0 : list.size();
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View view, ViewGroup parent) {
            ViewHodler vh;
            if (view == null) {
                vh = new ViewHodler();
                view = LayoutInflater.from(context).inflate(R.layout.home_item_city_two, null);
                vh.tv = (TextView) view.findViewById(R.id.g_title);
                vh.gv = (GridView) view.findViewById(R.id.gridview);
                vh.gl = view.findViewById(R.id.g_layout);
                view.setTag(vh);
            } else {
                vh = (ViewHodler) view.getTag();
            }

            if (list.get(position).getMenuItems() != null && list.get(position).getMenuItems().size() > 0) {
                vh.tv.setVisibility(View.VISIBLE);
                vh.gv.setVisibility(View.VISIBLE);
                vh.gl.setVisibility(View.VISIBLE);
                vh.tv.setText(list.get(position).getGroupName());
                tlist = list.get(position).getMenuItems();
                bodyItemAdapter = new BodyItemAdapter(context, tlist);
            } else {
                vh.tv.setVisibility(View.GONE);
                vh.gv.setVisibility(View.GONE);
                vh.gl.setVisibility(View.GONE);


            }
            vh.gv.setAdapter(bodyItemAdapter);
            ListViewUtils.calGridViewWidthAndHeigh(4, vh.gv, 70);
            vh.gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int index, long id) {
                    navigationSkip(list.get(position).getMenuItems().get(index));
                }
            });
            return view;
        }

        class ViewHodler {
            TextView tv;
            GridView gv;
            LinearLayout gl;
        }
    }

    class BodyItemAdapter extends BaseAdapter {
        Context context;
        List<CityBean.MenuItems.MenuItem> dataList;

        public List<CityBean.MenuItems.MenuItem> getDataList() {
            return dataList;
        }

        public void setDataList(List<CityBean.MenuItems.MenuItem> dataList) {
            this.dataList = dataList;
        }

        public BodyItemAdapter(Context context, List<CityBean.MenuItems.MenuItem> dataList) {
            this.context = context;
            this.dataList = dataList;
        }

        @Override
        public int getCount() {
            return dataList == null ? 0 : dataList.size();
        }

        @Override
        public Object getItem(int i) {
            if (i >= getCount()) {
                return null;
            }
            return i;
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            ItemViewHodler ivh;
            if (view == null) {
                ivh = new ItemViewHodler();
                view = LayoutInflater.from(context).inflate(R.layout.home_item_city_one, null);
                ivh.tv = (TextView) view.findViewById(R.id.title);
                ivh.iv = (ImageView) view.findViewById(R.id.icon);
                view.setTag(ivh);
            } else {
                ivh = (ItemViewHodler) view.getTag();
            }
            ivh.tv.setText(dataList.get(i).getItemName());

            Glide.with(context)
                    .load(dataList.get(i).getItemImg())
                    .apply(options)
                    .into(ivh.iv);

            return view;
        }

        class ItemViewHodler {
            TextView tv;
            ImageView iv;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        MPermissionUtils.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1) {
            //启动定位
            mLocationClient.startLocation();
        } else {
            Toasty.normal(getContext(), "您没有授权定位权限，请在手机设置中授权！", Toast.LENGTH_SHORT).show();
            resetWeather();
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            if (mLocationClient != null && mLocationClient.isStarted()) {
                mLocationClient.stopLocation();
            }
        } else {
            if (mLocationClient != null && !mLocationClient.isStarted()) {
                mLocationClient.startLocation();
            }
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        //baidu
        //umeng
        MobclickAgent.onPageStart("城事");
        MobclickAgent.onResume(getContext());
    }

    @Override
    public void onPause() {
        super.onPause();
        //baidu
        //umeng
        MobclickAgent.onPageEnd("城事");
        MobclickAgent.onPause(getContext());
    }
}
